package com.bigknow.appstore.proxy.handler.dispatcher;

import com.bigknow.appstore.proxy.cache.ICacheManager;
import com.bigknow.appstore.proxy.exceptions.processor.impl.ErrorAssert;
import com.bigknow.appstore.proxy.handler.base.BaseOutboundHandler;
import com.bigknow.appstore.proxy.log.ILogWriter;
import com.bigknow.appstore.proxy.server.IProxyServer;
import com.bigknow.appstore.proxy.util.HandlerVariables;
import com.bigknow.appstore.proxy.util.UriAndUrlHelper;
import com.bigknow.appstore.proxy.vo.RequestVo;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpResponse;

/**
 * 处理网站重定向
 * Created by chaos on 2016/9/21.
 */
@ChannelHandler.Sharable
public class LocationDispatcherHandler extends BaseOutboundHandler {
    public LocationDispatcherHandler(IProxyServer proxyServer, ICacheManager cacheManager, ILogWriter writer) {
        super(proxyServer, cacheManager, writer);
    }

    @Override
    public void write(ChannelHandlerContext ctx, FullHttpMessage msg, ChannelPromise promise) {
        ErrorAssert.assertFullHttpResponseMsg(ctx, msg
                , HandlerVariables.requestVoForCurrentResponse.get(ctx.channel().id().asLongText()));
        FullHttpResponse response = (FullHttpResponse) msg;
        String location = response.headers().get("location");
        if (location != null) {
            if (location.startsWith("http") || location.startsWith("https")) {
                //输入的http路径能够被找到的话就进行处理
                String url = findAndCreateCurrentUrl(location);
                if (url != null) {
                    response.headers().set("location", url);
                }
            } else {
                RequestVo requestVo = HandlerVariables.requestVoForCurrentResponse.get(ctx.channel().id().asLongText());
                //如果requestVo不为空，并且uri是初次方位的uri，这里就解决一个bug
                //当页面自动跳转的时候由于大多数网站都是只有域名的会搞掉version部分的path，这里进行补全
                if (requestVo != null && requestVo.isRootUri()) {
                    String url = UriAndUrlHelper.getHostUrl(proxyServer
                            //requestVo.getCallUri() 在这里必然是服务器的路径
                            , UriAndUrlHelper.getStandardUri(requestVo.getCallUri())) + "/"
                            + UriAndUrlHelper.getCurrentLocation(requestVo, location);
                    response.headers().set("location", url);
                }
            }
        }
        ctx.write(msg, promise);
    }
}
